﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using Telerik.WinControls.UI;
using System.IO;
using Telerik.WinControls.Data;
using log4net;
using System.Collections;
using System.Text.RegularExpressions;

namespace QuanLyNhaSach
{
    public partial class frmHoaDonMuaHang : Form
    {
        //Tao Parttern Seleton
        static frmHoaDonMuaHang doituong = null;
        public static frmHoaDonMuaHang TaoDoiTuong()
        {
            if (doituong == null)
                doituong = new frmHoaDonMuaHang();
            return doituong;
        }

        public frmHoaDonMuaHang()
        {
            InitializeComponent();
        }

        #region "khai báo biến"
        //public event EventHandler xoahang;
        sv_QuanLyNhaSach.AdapterClient xuly = new sv_QuanLyNhaSach.AdapterClient();
        private ILog logger;
        int vitri;
        ArrayList test_DSNCC;
        ArrayList test_DSKho;

        double tongtien = 0;
        double tongtienhang = 0;
        double tienDaDua = 0;
        double tienthue = 0;
        double tienConLai = 0;

        float mucThue;

        string mahang;
        string tenhang;
        string dongia;
        string soluong;
        float chietkhau;
        string thanhtien;
        string dvt;
        public string manv = frmDangNhap.maNV_FromDangNhap;        
        #endregion

        #region "Ham chuyen so thanh chu"
        private static string Chu(string gNumber)
        {
            string result = "";
            switch (gNumber)
            {
                case "0":
                    result = "không";
                    break;
                case "1":
                    result = "một";
                    break;
                case "2":
                    result = "hai";
                    break;
                case "3":
                    result = "ba";
                    break;
                case "4":
                    result = "bốn";
                    break;
                case "5":
                    result = "năm";
                    break;
                case "6":
                    result = "sáu";
                    break;
                case "7":
                    result = "bảy";
                    break;
                case "8":
                    result = "tám";
                    break;
                case "9":
                    result = "chín";
                    break;
            }
            return result;
        }
        private static string Donvi(string so)
        {
            string Kdonvi = "";

            if (so.Equals("1"))
                Kdonvi = "";
            if (so.Equals("2"))
                Kdonvi = "nghìn";
            if (so.Equals("3"))
                Kdonvi = "triệu";
            if (so.Equals("4"))
                Kdonvi = "tỷ";
            if (so.Equals("5"))
                Kdonvi = "nghìn tỷ";
            if (so.Equals("6"))
                Kdonvi = "triệu tỷ";
            if (so.Equals("7"))
                Kdonvi = "tỷ tỷ";

            return Kdonvi;
        }
        private static string Tach(string tach3)
        {

            string Ktach = "";
            if (tach3.Equals("000"))
                return "";
            if (tach3.Length == 3)
            {
                try
                {
                    string tr = tach3.Trim().Substring(0, 1).ToString().Trim();
                    string ch = tach3.Trim().Substring(1, 1).ToString().Trim();
                    string dv = tach3.Trim().Substring(2, 1).ToString().Trim();
                    if (tr.Equals("0") && ch.Equals("0"))
                        Ktach = " không trăm lẻ " + Chu(dv.ToString().Trim()) + " ";
                    if (!tr.Equals("0") && ch.Equals("0") && dv.Equals("0"))
                        Ktach = Chu(tr.ToString().Trim()).Trim() + " trăm ";
                    if (!tr.Equals("0") && ch.Equals("0") && !dv.Equals("0"))
                        Ktach = Chu(tr.ToString().Trim()).Trim() + " trăm lẻ " + Chu(dv.Trim()).Trim() + " ";
                    if (tr.Equals("0") && Convert.ToInt32(ch) > 1 && Convert.ToInt32(dv) > 0 && !dv.Equals("5"))
                        Ktach = " không trăm " + Chu(ch.Trim()).Trim() + " mươi " + Chu(dv.Trim()).Trim() + " ";
                    if (tr.Equals("0") && Convert.ToInt32(ch) > 1 && dv.Equals("0"))
                        Ktach = " không trăm " + Chu(ch.Trim()).Trim() + " mươi ";
                    if (tr.Equals("0") && Convert.ToInt32(ch) > 1 && dv.Equals("5"))
                        Ktach = " không trăm " + Chu(ch.Trim()).Trim() + " mươi lăm ";
                    if (tr.Equals("0") && ch.Equals("1") && Convert.ToInt32(dv) > 0 && !dv.Equals("5"))
                        Ktach = " không trăm mười " + Chu(dv.Trim()).Trim() + " ";
                    if (tr.Equals("0") && ch.Equals("1") && dv.Equals("0"))
                        Ktach = " không trăm mười ";
                    if (tr.Equals("0") && ch.Equals("1") && dv.Equals("5"))
                        Ktach = " không trăm mười lăm ";
                    if (Convert.ToInt32(tr) > 0 && Convert.ToInt32(ch) > 1 && Convert.ToInt32(dv) > 0 && !dv.Equals("5"))
                        Ktach = Chu(tr.Trim()).Trim() + " trăm " + Chu(ch.Trim()).Trim() + " mươi " + Chu(dv.Trim()).Trim() + " ";
                    if (Convert.ToInt32(tr) > 0 && Convert.ToInt32(ch) > 1 && dv.Equals("0"))
                        Ktach = Chu(tr.Trim()).Trim() + " trăm " + Chu(ch.Trim()).Trim() + " mươi ";
                    if (Convert.ToInt32(tr) > 0 && Convert.ToInt32(ch) > 1 && dv.Equals("5"))
                        Ktach = Chu(tr.Trim()).Trim() + " trăm " + Chu(ch.Trim()).Trim() + " mươi lăm ";
                    if (Convert.ToInt32(tr) > 0 && ch.Equals("1") && Convert.ToInt32(dv) > 0 && !dv.Equals("5"))
                        Ktach = Chu(tr.Trim()).Trim() + " trăm mười " + Chu(dv.Trim()).Trim() + " ";

                    if (Convert.ToInt32(tr) > 0 && ch.Equals("1") && dv.Equals("0"))
                        Ktach = Chu(tr.Trim()).Trim() + " trăm mười ";
                    if (Convert.ToInt32(tr) > 0 && ch.Equals("1") && dv.Equals("5"))
                        Ktach = Chu(tr.Trim()).Trim() + " trăm mười lăm ";
                }
                catch
                {
                }

            }
            return Ktach;

        }


        public static string So_chu(double gNum)
        {
            if (gNum == 0)
                return "Không đồng";

            string lso_chu = "";
            string tach_mod = "";
            string tach_conlai = "";
            double Num = Math.Round(gNum, 0);
            string gN = Convert.ToString(Num);
            int m = Convert.ToInt32(gN.Length / 3);
            int mod = gN.Length - m * 3;
            string dau = "[+]";

            // Dau [+ , - ]
            if (gNum < 0)
                dau = "[-]";
            dau = "";

            // Tach hang lon nhat
            if (mod.Equals(1))
                tach_mod = "00" + Convert.ToString(Num.ToString().Trim().Substring(0, 1)).Trim();
            if (mod.Equals(2))
                tach_mod = "0" + Convert.ToString(Num.ToString().Trim().Substring(0, 2)).Trim();
            if (mod.Equals(0))
                tach_mod = "000";
            // Tach hang con lai sau mod :
            if (Num.ToString().Length > 2)
                tach_conlai = Convert.ToString(Num.ToString().Trim().Substring(mod, Num.ToString().Length - mod)).Trim();

            ///don vi hang mod 
            int im = m + 1;
            if (mod > 0)
                lso_chu = Tach(tach_mod).ToString().Trim() + " " + Donvi(im.ToString().Trim());
            /// Tach 3 trong tach_conlai

            int i = m;
            int _m = m;
            int j = 1;
            string tach3 = "";
            string tach3_ = "";

            while (i > 0)
            {
                tach3 = tach_conlai.Trim().Substring(0, 3).Trim();
                tach3_ = tach3;
                lso_chu = lso_chu.Trim() + " " + Tach(tach3.Trim()).Trim();
                m = _m + 1 - j;
                if (!tach3_.Equals("000"))
                    lso_chu = lso_chu.Trim() + " " + Donvi(m.ToString().Trim()).Trim();
                tach_conlai = tach_conlai.Trim().Substring(3, tach_conlai.Trim().Length - 3);

                i = i - 1;
                j = j + 1;
            }
            if (lso_chu.Trim().Substring(0, 1).Equals("k"))
                lso_chu = lso_chu.Trim().Substring(10, lso_chu.Trim().Length - 10).Trim();
            if (lso_chu.Trim().Substring(0, 1).Equals("l"))
                lso_chu = lso_chu.Trim().Substring(2, lso_chu.Trim().Length - 2).Trim();
            if (lso_chu.Trim().Length > 0)
                lso_chu = dau.Trim() + " " + lso_chu.Trim().Substring(0, 1).Trim().ToUpper() + lso_chu.Trim().Substring(1, lso_chu.Trim().Length - 1).Trim() + " đồng chẵn.";

            return lso_chu.ToString().Trim();

        }
        #endregion

        private void TextBoxKeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private bool ktmh(string mamh)
        {
            DataSet ds = new DataSet();
            ds.ReadXml(new StringReader(xuly.selectqueryByText("select mamh from mathang where mamh like'" + mamh.Trim() + "'")));
            if (ds.Tables.Count > 0)
            {
                return true;
            }
            return false;
        }

        private void frmHoaDonMuaHang_Load(object sender, EventArgs e)
        {
            logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            this.KeyDown += new KeyEventHandler(frmHoaDonMuaHang_KeyDown);
            txt_chungtu.KeyDown += new KeyEventHandler(txt_chungtu_KeyDown);
            cmb_khohang.KeyDown += new KeyEventHandler(cmb_khohang_KeyDown);
            cmb_nhacungcap.KeyDown += new KeyEventHandler(cmb_nhacungcap_KeyDown);
            cmb_tenmathang.KeyDown += new KeyEventHandler(cmb_tenmathang_KeyDown);
            txt_soluong.KeyDown += new KeyEventHandler(txt_soluong_KeyDown);
            txt_dongia.KeyDown += new KeyEventHandler(txt_soluong_KeyDown);
            txt_tiendadua.KeyDown += new KeyEventHandler(txt_tiendadua_KeyDown);
            txt_mucthue.KeyDown += new KeyEventHandler(txt_mucthue_KeyDown);
            bt_them.KeyDown += new KeyEventHandler(bt_them_KeyDown);
            bt_chuyenxuong.KeyDown += new KeyEventHandler(bt_chuyenxuong_KeyDown);

            try
            {
                //set ngay thang hien tai
                dtp_ngaynhap.Value = DateTime.Now;

                //focus vao so chung tu
                txt_chungtu.Focus();

                //set ten nhan vien
                DataSet ds_TenNhanVien = new DataSet();
                ds_TenNhanVien.ReadXml(new StringReader(xuly.selectqueryByText("select HoTenNV from NhanVien where MaNV = '" + frmDangNhap.maNV_FromDangNhap + "'")));
                if (ds_TenNhanVien.Tables.Count > 0)
                    txt_nhanvien.Text = ds_TenNhanVien.Tables[0].Rows[0][0].ToString();               

                //Load 
                LoadDuLieu();

                //Load ds Phieu DH NCC
                Load_DSPhieuDatNCCChuaGiao();
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        void bt_chuyenxuong_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                cmb_tenmathang.Focus();
        }

        void bt_them_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                Luu();
        }

        void txt_mucthue_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                txt_tiendadua.Focus();
                txt_tiendadua.SelectionStart = txt_tiendadua.Text.Length;
            }
        }

        void txt_tiendadua_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                bt_them.Focus();
        }

        void txt_soluong_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                bt_chuyenxuong.Focus();
        }

        void cmb_tenmathang_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                txt_soluong.Focus();
                txt_soluong.SelectionStart = txt_soluong.Text.Length;
            }
        }

        void cmb_nhacungcap_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                cmb_tenmathang.Focus();
        }

        void cmb_khohang_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                cmb_nhacungcap.Focus();
        }

        void txt_chungtu_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                cmb_khohang.Focus();
        }

        void frmHoaDonMuaHang_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.F2)
            {
                txt_tiendadua.Focus();
                txt_tiendadua.SelectionStart = txt_tiendadua.Text.Length;
            }
            if (e.KeyData == Keys.F3)
            {
                Luu();
            }
        }

        private void LoadDuLieu()
        {
            try
            {
                //Chinh do dai cua cac cot trong muiltcombobox
                RadMultiColumnComboBoxElement multicbb_kho = this.cmb_khohang.MultiColumnComboBoxElement;
                RadMultiColumnComboBoxElement multicbb_nhacungcap = this.cmb_nhacungcap.MultiColumnComboBoxElement;
                RadMultiColumnComboBoxElement multicbb_mathang = this.cmb_tenmathang.MultiColumnComboBoxElement;
                multicbb_mathang.AutoCompleteMode = AutoCompleteMode.None;
                multicbb_kho.DropDownSizingMode = SizingMode.UpDownAndRightBottom;
                multicbb_nhacungcap.DropDownSizingMode = SizingMode.UpDownAndRightBottom;
                multicbb_mathang.DropDownSizingMode = SizingMode.UpDownAndRightBottom;
                multicbb_kho.DropDownMinSize = new Size(300, 300);
                multicbb_nhacungcap.DropDownMinSize = new Size(500, 200);
                multicbb_mathang.DropDownMinSize = new Size(600, 200);
                //load mat hang
                DataSet ds = new DataSet();
                ds.ReadXml(new StringReader(xuly.selectqueryByText("select mamh,tenmh from MatHang")));
                if (ds.Tables.Count > 0)
                {
                    cmb_tenmathang.DataSource = ds.Tables[0];
                    cmb_tenmathang.DisplayMember = "tenmh";
                    cmb_tenmathang.ValueMember = "mamh";
                    cmb_tenmathang.SelectedIndex = -1;
                }
                FilterDescriptor des_mh = new FilterDescriptor(this.cmb_tenmathang.DisplayMember, FilterOperator.StartsWith, string.Empty);
                cmb_tenmathang.EditorControl.FilterDescriptors.Add(des_mh);
                //load kho hang
                DataSet ds1 = new DataSet();
                ds1.ReadXml(new StringReader(xuly.selectqueryByText("select makho,tenkho from kho")));
                if (ds1.Tables.Count > 0)
                {
                    test_DSKho = new ArrayList();
                    for (int i = 0; i < ds1.Tables[0].Rows.Count; i++)
                    {
                        test_DSKho.Add(ds1.Tables[0].Rows[i]["TenKho"].ToString().Trim());
                    }

                    cmb_khohang.DataSource = ds1.Tables[0];
                    cmb_khohang.DisplayMember = "tenkho";
                    cmb_khohang.ValueMember = "makho";
                    cmb_khohang.SelectedIndex = -1;
                }
                FilterDescriptor des_khoh = new FilterDescriptor(this.cmb_khohang.DisplayMember, FilterOperator.StartsWith, string.Empty);
                cmb_khohang.EditorControl.FilterDescriptors.Add(des_khoh);
                //load nha cung cap
                DataSet ds2 = new DataSet();
                ds2.ReadXml(new StringReader(xuly.selectqueryByText("select mancc,tenncc, diachincc from NhaCungCap")));
                if (ds2.Tables.Count > 0)
                {
                    test_DSNCC = new ArrayList();
                    for (int i = 0; i < ds2.Tables[0].Rows.Count; i++)
                    {
                        test_DSNCC.Add(ds2.Tables[0].Rows[i]["TenNCC"].ToString().Trim());
                    }

                    cmb_nhacungcap.DataSource = ds2.Tables[0];
                    cmb_nhacungcap.DisplayMember = "tenncc";
                    cmb_nhacungcap.ValueMember = "mancc";
                    cmb_nhacungcap.SelectedIndex = -1;
                }
                FilterDescriptor des_ncc = new FilterDescriptor(this.cmb_nhacungcap.DisplayMember, FilterOperator.StartsWith, string.Empty);
                cmb_nhacungcap.EditorControl.FilterDescriptors.Add(des_ncc);
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        private string xulyma()
        {            
            DataSet ds_tam = new DataSet();
            string mamoi="";
            try
            {
                string chuoi = "NH" + DateTime.Today.Year.ToString("0000") + DateTime.Today.Month.ToString("00");
                ds_tam.ReadXml(new StringReader(xuly.selectqueryByText("select top 1 mahdnh from hoadonnhaphang where mahdnh like '%" + chuoi + "%'order by mahdnh desc")));
                if (ds_tam.Tables.Count == 0)
                    mamoi = chuoi + "0001";
                else
                {
                    string matam = ds_tam.Tables[0].Rows[0][0].ToString();
                    string kituso = matam.Substring(8, 4).ToString();
                    int somoi = int.Parse(kituso) + 1;
                    mamoi = chuoi + somoi.ToString("0000");
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
            return mamoi;
        }    

        private void cmb_nhacungcap_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (cmb_nhacungcap.Text == "")
                {
                    txt_diachi.Text = "";
                }
                else
                {
                    txt_diachi.Text = cmb_nhacungcap.EditorControl.Rows[cmb_nhacungcap.SelectedIndex].Cells["DiaChiNCC"].Value.ToString();
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        private void bt_chuyenxuong_Click(object sender, EventArgs e)
        {
            errorProvider1.Clear();
            if (txt_mahang.Text.Trim() == "")
            {
                errorProvider1.SetError(txt_mahang, "Chưa chọn mặt hàng");
                cmb_tenmathang.Focus();
                return;
            }
            if (ktmh(txt_mahang.Text.Trim()) == false)
            {
                errorProvider1.SetError(txt_mahang, "Mặt hàng không hợp lệ");
                cmb_tenmathang.Focus();
                return;
            }
            if (txt_soluong.Text.Trim() == "" || double.Parse(txt_soluong.Text) == 0)
            {
                errorProvider1.SetError(txt_soluong, "Đơn giá không hợp lệ");
                txt_soluong.Focus();
                return;
            }
            if (txt_dongia.Text.Trim() == "")
            {
                errorProvider1.SetError(txt_dongia, "Đơn giá không hợp lệ");
                txt_dongia.Focus();
                return;
            }
            try
            {
                //Tang so luong va thay doi tong thanh tien + Truong hop gia tien khac nhau
                if (gv_hdnhaphang.Rows.Count > 0)
                {

                    for (int i = 0; i < gv_hdnhaphang.Rows.Count; i++)
                    {
                        if (cmb_tenmathang.SelectedValue.ToString().Trim() == gv_hdnhaphang.Rows[i].Cells["mamh"].Value.ToString().Trim() && txt_dongia.Text.Trim() == gv_hdnhaphang.Rows[i].Cells["DonGia"].Value.ToString().Trim())
                        {
                            gv_hdnhaphang.Rows[i].Cells["soluong"].Value = (int.Parse(gv_hdnhaphang.Rows[i].Cells["soluong"].Value.ToString()) + int.Parse(txt_soluong.Text.Trim())).ToString("#,##0");
                            gv_hdnhaphang.Rows[i].Cells["thanhtien"].Value = (int.Parse(gv_hdnhaphang.Rows[i].Cells["soluong"].Value.ToString()) * double.Parse(gv_hdnhaphang.Rows[i].Cells["dongia"].Value.ToString()) - int.Parse(gv_hdnhaphang.Rows[i].Cells["soluong"].Value.ToString()) * double.Parse(gv_hdnhaphang.Rows[i].Cells["dongia"].Value.ToString()) * double.Parse(gv_hdnhaphang.Rows[i].Cells["chietkhau"].Value.ToString()) / 100).ToString("#,##0");
                            //Tinh tong tien hang
                            tongtienhang = 0;
                            for (int j = 0; j < gv_hdnhaphang.Rows.Count; j++)
                            {
                                tongtienhang += double.Parse(gv_hdnhaphang.Rows[j].Cells["ThanhTien"].Value.ToString());
                            }
                            txt_tongtienhang.Text = tongtienhang.ToString("#,##0");
                            cmb_tenmathang.Focus();
                            return;
                        }
                    }
                }
                //Khai bao bien
                mahang = txt_mahang.Text;
                tenhang = cmb_tenmathang.Text.Trim();
                soluong = txt_soluong.Text;
                dongia = txt_dongia.Text;
                chietkhau = float.Parse(txt_khuyenmai.Text) / 100;
                thanhtien = txt_thanhtien1.Text;
                if (gv_hdnhaphang.Rows.Count != 0)
                    vitri = gv_hdnhaphang.Rows.Count;
                else
                    vitri = 0;
                //Tang so luong va thay doi tong thanh tien
                for (int i = 0; i < gv_hdnhaphang.Rows.Count; i++)
                {
                    if (cmb_tenmathang.SelectedValue.ToString().Trim() == gv_hdnhaphang.Rows[i].Cells["mamh"].Value.ToString().Trim())
                    {
                        gv_hdnhaphang.Rows[i].Cells["soluong"].Value = (int.Parse(gv_hdnhaphang.Rows[i].Cells["soluong"].Value.ToString()) + int.Parse(txt_soluong.Text.Trim())).ToString("#,##0");
                        gv_hdnhaphang.Rows[i].Cells["thanhtien"].Value = (int.Parse(gv_hdnhaphang.Rows[i].Cells["soluong"].Value.ToString()) * double.Parse(gv_hdnhaphang.Rows[i].Cells["dongia"].Value.ToString())).ToString("#,##0");
                        //gv_hdnhaphang.Rows[i].Cells["thanhtien"].Value = double.Parse(gv_hdnhaphang.Rows[i].Cells["thanhtien"].Value.ToString()).ToString("#,##0");
                        if (i == gv_hdnhaphang.Rows.Count - 1)
                        {
                            txt_tongtienhang.Text = double.Parse(gv_hdnhaphang.Rows[i].Cells["thanhtien"].Value.ToString()).ToString("#,##0");
                            tongtien = double.Parse(txt_tongtienhang.Text);
                        }
                        cmb_tenmathang.Focus();
                        return;
                    }
                }
                //Them mat hang xuong gridview                
                gv_hdnhaphang.Rows.AddNew();                
                gv_hdnhaphang.Rows[vitri].Cells["MaMH"].Value = mahang;
                gv_hdnhaphang.Rows[vitri].Cells["TenMH"].Value = tenhang;
                gv_hdnhaphang.Rows[vitri].Cells["SoLuong"].Value = soluong;
                gv_hdnhaphang.Rows[vitri].Cells["DonGia"].Value = dongia;
                gv_hdnhaphang.Rows[vitri].Cells["ChietKhau"].Value = chietkhau;
                gv_hdnhaphang.Rows[vitri].Cells["ThanhTien"].Value = thanhtien;
                //Them nut xoa trong Gridview
                if (gv_hdnhaphang.Columns.GetColumnByFieldName("xoa").Length == 0)
                {
                    GridViewCommandColumn btnColumn = new GridViewCommandColumn();
                    btnColumn.FieldName = "xoa";
                    btnColumn.Name = "xoa";
                    btnColumn.UseDefaultText = true;
                    btnColumn.DefaultText = "Xóa";
                    gv_hdnhaphang.Columns.Insert(gv_hdnhaphang.Columns.Count, btnColumn);
                }
                //Tao STT cho Girdview
                if (gv_hdnhaphang.Rows.Count > 0)
                {
                    tongtienhang = 0;
                    tongtien = 0;
                    for (int i = 0; i < gv_hdnhaphang.Rows.Count; i++)
                    {
                        gv_hdnhaphang.Rows[i].Cells["STT"].Value = i + 1;
                        //Tinh Tong Tien
                        tongtienhang += double.Parse(gv_hdnhaphang.Rows[i].Cells["ThanhTien"].Value.ToString());
                    }
                    txt_tongtienhang.Text = tongtienhang.ToString("#,##0");
                    tongtien = tongtienhang + double.Parse(txt_tienthue.Text);
                    txt_tongthanhtientinhthue.Text = tongtien.ToString("#,##0");
                    txt_tienbangchu.Text = So_chu(tongtien);
                }                

                //Xoa bo thong tin trong cac o mat hang
                txt_mahang.Text = "";
                cmb_tenmathang.SelectedIndex = -1;
                txt_soluong.Text = "1";
                txt_dongia.Text = "0";
                ddl_dvt.Text = "";
                txt_thanhtien1.Text = "0";
                txt_khuyenmai.Text = "0";
                cmb_tenmathang.Focus();
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }
        
        private void cmb_tenmathang_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (cmb_tenmathang.Text == "")
                {
                    txt_mahang.Text = "";
                    txt_dongia.Text = "0";
                    txt_soluong.Text = "1";
                    txt_thanhtien1.Text = "0";
                    ddl_dvt.Text = "";
                    txt_khuyenmai.Text = "0";
                }
                else
                {
                    DataSet ds = new DataSet();
                    ds.ReadXml(new StringReader(xuly.selectqueryByText("select MaMH, DonGiaNhap,dvt from MatHang where MaMH = '" + cmb_tenmathang.SelectedValue.ToString().Trim() + "'")));
                    if (ds.Tables.Count > 0)
                    {
                        double dongiaMatHang = double.Parse(ds.Tables[0].Rows[0]["DonGiaNhap"].ToString());
                        if (cmb_tenmathang.SelectedIndex != -1)
                        {
                            txt_mahang.Text = ds.Tables[0].Rows[0]["MaMH"].ToString();
                            txt_dongia.Text = dongiaMatHang.ToString("#,##0");
                            ddl_dvt.Text = ds.Tables[0].Rows[0]["DVT"].ToString();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }            
        }        

        private void bt_them_Click(object sender, EventArgs e)
        {
            Luu();

        }

        private void Luu()
        {
            errorProvider1.Clear();
            lbl_ThongBao.Text = "Thông báo!";
            if (txt_chungtu.Text.Trim() == "")
            {
                errorProvider1.SetError(txt_chungtu, "Vui lòng nhập thông tin chứng từ.");
                txt_chungtu.Focus();
                return;
            }
            if (cmb_khohang.Text.Trim() == "")
            {
                errorProvider1.SetError(cmb_khohang, "Chưa chọn kho hàng");
                cmb_khohang.Focus();
                return;
            }
            if (test_DSKho.Contains(cmb_khohang.Text.Trim()) == false)
            {
                errorProvider1.SetError(cmb_khohang, "Nhập sai thông tin Kho Hàng.");
                cmb_khohang.Focus();
                return;
            }
            if (cmb_nhacungcap.Text.Trim() == "")
            {
                errorProvider1.SetError(cmb_nhacungcap, "Chưa chọn NCC");
                cmb_nhacungcap.Focus();
                return;
            }
            if (test_DSNCC.Contains(cmb_nhacungcap.Text.Trim()) == false)
            {
                errorProvider1.SetError(cmb_nhacungcap, "Nhập sai thông tin Nhà Cung Cấp");
                cmb_nhacungcap.Focus();
                return;
            }
            if (gv_hdnhaphang.Rows.Count == 0)
            {
                lbl_ThongBao.Text = "Chưa có dữ liệu chi tiết mua hàng";
                errorProvider1.SetError(lbl_ThongBao, "Vui lòng nhập thông tin chi tiết mặt hàng");
                return;
            }
            else
            {
                #region "Kiem tra thông tin từng cell tren lưới"
                for (int i = 0; i < gv_hdnhaphang.Rows.Count; i++)
                {
                    try
                    {
                        if (Regex.IsMatch(gv_hdnhaphang.Rows[i].Cells["SoLuong"].Value.ToString().Trim(), @"^[0-9,',']{0,5}$") == false || int.Parse(gv_hdnhaphang.CurrentRow.Cells["SoLuong"].Value.ToString()) < 0)
                        {
                            lbl_ThongBao.Text = "Số lượng nhập vào phải lớn hơn không (số lượng > 0) và là con số nguyên. Vui lòng nhập lại";
                            errorProvider1.RightToLeft = false;
                            errorProvider1.SetError(lbl_ThongBao, "Xem lại thông tin trên lưới.");
                            return;
                        }
                        if (Regex.IsMatch(gv_hdnhaphang.Rows[i].Cells["DonGia"].Value.ToString(), @"^[0-9,',']{0,9}$") == false)
                        {
                            lbl_ThongBao.Text = "Đơn giá nhập vào là số nguyên không âm. Vui lòng nhập lại";
                            errorProvider1.RightToLeft = false;
                            errorProvider1.SetError(lbl_ThongBao, "Xem lại thông tin trên lưới.");
                            return;
                        }
                        if (Regex.IsMatch(gv_hdnhaphang.Rows[i].Cells["Chietkhau"].Value.ToString().Trim(), @"^\d{1,2}$") == false || int.Parse(gv_hdnhaphang.CurrentRow.Cells["ChietKhau"].Value.ToString()) > 50)
                        {
                            lbl_ThongBao.Text = "Số chiết khấu từ 0 - 50 %";
                            errorProvider1.RightToLeft = false;
                            errorProvider1.SetError(lbl_ThongBao, "Xem lại thông tin trên lưới.");
                            return;
                        }
                        lbl_ThongBao.Text = "Thông báo!";
                        errorProvider1.RightToLeft = true;
                    }
                    catch (Exception ex)
                    {
                        logger.Error("Error: " + ex.Message);
                    }
                }
                #endregion
            }
            //if (dtp_ngayhenthanhtoan.Value < DateTime.Now)
            //{
            //    errorProvider1.SetError(dtp_ngayhenthanhtoan, "Ngày hẹn thanh toán không được nhỏ hơn ngày hiện tại");
            //    dtp_ngayhenthanhtoan.Focus();
            //    return;
            //}

            try
            {
                //Khai bao thong tin bien luu vao CSDL
                string mahd = xulyma();
                string makho = cmb_khohang.SelectedValue.ToString();
                string mancc = cmb_nhacungcap.SelectedValue.ToString();
                string sochungtu = txt_chungtu.Text;
                DateTime ngaylap = dtp_ngaynhap.Value;
                mucThue = float.Parse(txt_mucthue.Text) / 100;
                string ghichu = txt_ghichu.Text;
                string diachi = txt_diachi.Text;
                double tongtientinhthue = tongtien;
                double dadua = tienDaDua;
                double conlai = tienConLai;
                //DateTime hanthanhtoan = dtp_ngayhenthanhtoan.Value;
                DateTime hanthanhtoan = DateTime.Now;

                if (!xuly.InsertHDNH(mahd, mancc, makho.Trim(), manv, ngaylap, sochungtu, mucThue, tongtientinhthue, dadua, conlai, hanthanhtoan))
                {
                    MessageBox.Show("Lưu thất bại! Vui lòng kiểm tra lại thông tin mặt hàng hoặc gặp kỹ thuật.", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    return;
                }
                //Duyet qua Gridview de them vao bang Chi Tiet hoá đơn nhập
                for (int i = 0; i < gv_hdnhaphang.Rows.Count; i++)
                {
                    string mamh = gv_hdnhaphang.Rows[i].Cells["MaMH"].Value.ToString().Trim();
                    int soluong = int.Parse(gv_hdnhaphang.Rows[i].Cells["SoLuong"].Value.ToString());
                    double dongia = double.Parse(gv_hdnhaphang.Rows[i].Cells["DonGia"].Value.ToString());
                    float chietkhau = float.Parse(gv_hdnhaphang.Rows[i].Cells["ChietKhau"].Value.ToString()) / 100;
                    double thanhtien = double.Parse(gv_hdnhaphang.Rows[i].Cells["ThanhTien"].Value.ToString());
                    //Them tung chi tiet vao CT hoa đơn nhập
                    if (!xuly.InsertCTNH(mamh, mahd, soluong, dongia, chietkhau, thanhtien))
                    {
                        MessageBox.Show("Lưu thất bại! Vui lòng kiểm tra lại thông tin mặt hàng hoặc gặp kỹ thuật.", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                        return;
                    }
                    else
                    {
                        if (checkbox_PhieuDHNCC.Checked == true)
                        {
                            //Cap Nhật lại Mặt hàng đã giao trong đơn đặt hàng NCC
                            xuly.selectqueryByText("update CTDatHangNCC set DaGiao = 'true' where MaDHNCC = '" + mcbb_PhieuDHNCC.SelectedValue.ToString().Trim() + "' and MaMH = '" + mamh + "' ");
                        }
                    }
                }
                MessageBox.Show("Lưu thành công", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //In phieu sau khi luu da dc Kich
                if (chb_inphieu.Checked == true)
                {
                    //Dua len Report    
                    Report.frm_InPhieuNhap phieunhap = new Report.frm_InPhieuNhap();
                    phieunhap.mahdnhap = mahd;
                    phieunhap.ShowDialog();

                    //Xoa cac thong tin tien sau khi da luu va in phieu
                    txt_tongtienhang.Text = "0";
                    txt_tongthanhtientinhthue.Text = "0";
                    txt_mucthue.Text = "0";
                    txt_tiendadua.Text = "0";
                    txt_tienconlai.Text = "0";
                    txt_tienthue.Text = "0";
                    txt_tienbangchu.Text = "không đồng chẳn.";
                    if (checkbox_PhieuDHNCC.Checked == false)
                        gv_hdnhaphang.Rows.Clear();
                    txt_chungtu.Focus();
                }

                //Xoa tat cac thong tin sau khi da Luu hoa don va In phieu
                if (checkbox_PhieuDHNCC.Checked == true)
                {
                    Load_DSPhieuDatNCCChuaGiao();
                    gv_hdnhaphang.DataSource = null;
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        private void txt_mucthue_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (txt_mucthue.Text.Length != 0)
                {
                    double tienthueTam = tongtien / double.Parse(txt_mucthue.Text);
                    txt_tienthue.Text = tienthueTam.ToString("#,##0");

                    txt_tongthanhtientinhthue.Text = (tongtien + tienthueTam).ToString("#,##0");
                    txt_tienbangchu.Text = So_chu(double.Parse(txt_tongthanhtientinhthue.Text));
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }

        }

        private void txt_soluong_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (txt_soluong.Text.Length != 0)
                {
                    txt_soluong.Text = double.Parse(txt_soluong.Text).ToString("#,##0");
                    double thanhtien = double.Parse(txt_soluong.Text) * double.Parse(txt_dongia.Text) - double.Parse(txt_soluong.Text) * double.Parse(txt_dongia.Text) * float.Parse(txt_khuyenmai.Text) / 100;
                    txt_thanhtien1.Text = thanhtien.ToString("#,##0");
                }
                txt_soluong.SelectionStart = txt_soluong.Text.Length;                
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        private void txt_tiendadua_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (txt_tiendadua.Text.Length != 0)
                {
                    txt_tiendadua.Text = double.Parse(txt_tiendadua.Text).ToString("#,##0");                    

                    tienConLai = tongtien - double.Parse(txt_tiendadua.Text);
                    txt_tienconlai.Text = tienConLai.ToString("#,##0");

                    tienConLai = double.Parse(txt_tongthanhtientinhthue.Text) - double.Parse(txt_tiendadua.Text);
                    txt_tienconlai.Text = tienConLai.ToString("#,##0");
                }
                //cho con tro ve cuoi textbox
                txt_tiendadua.SelectionStart = txt_tiendadua.Text.Length;
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }

        }

        private void txt_dongia_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (txt_dongia.Text.Length != 0)
                {
                    txt_dongia.Text = double.Parse(txt_dongia.Text).ToString("#,##0");
                    double thanhtien = double.Parse(txt_soluong.Text) * double.Parse(txt_dongia.Text) - double.Parse(txt_soluong.Text) * double.Parse(txt_dongia.Text) * float.Parse(txt_khuyenmai.Text) / 100;
                    txt_thanhtien1.Text = thanhtien.ToString("#,##0");
                }
                //cho con tro ve cuoi textbox
                txt_dongia.SelectionStart = txt_dongia.Text.Length;
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        private void gv_hdnhaphang_CommandCellClick(object sender, EventArgs e)
        {
            double tongtien_sauxoa = 0;
            try
            {
                if (MessageBox.Show("Bạn muốn xóa chi tiết này?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    if (gv_hdnhaphang.Rows.Count == 1)
                    {
                        gv_hdnhaphang.Rows.Clear();
                    }
                    else
                    {
                        gv_hdnhaphang.Rows.RemoveAt(gv_hdnhaphang.CurrentRow.Index);
                        for (int i = 0; i < gv_hdnhaphang.Rows.Count; i++)
                        {
                            gv_hdnhaphang.Rows[i].Cells["STT"].Value = i + 1;
                        }
                    }
                    for (int j = 0; j < gv_hdnhaphang.Rows.Count; j++)
                    {
                        tongtien_sauxoa += double.Parse(gv_hdnhaphang.Rows[j].Cells["ThanhTien"].Value.ToString());
                    }
                    txt_tongtienhang.Text = tongtien_sauxoa.ToString("#,##0");
                    if (txt_mucthue.Text.Length != 0)
                    {
                        if (txt_tongtienhang.Text.Length != 0)
                        {
                            tienthue = double.Parse(txt_tongtienhang.Text) * double.Parse(txt_mucthue.Text) / 100;
                            txt_tienthue.Text = tienthue.ToString("#,##0");
                            txt_tongthanhtientinhthue.Text = (double.Parse(txt_tongtienhang.Text) + tienthue - double.Parse(txt_TienTamUng.Text)).ToString("#,##0");
                            txt_tienbangchu.Text = So_chu(double.Parse(txt_tongthanhtientinhthue.Text));
                        }
                    }
                    else
                    {
                        txt_tienthue.Text = "0";
                        txt_tongthanhtientinhthue.Text = txt_tongtienhang.Text;
                        txt_tienbangchu.Text = So_chu(double.Parse(txt_tongthanhtientinhthue.Text));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        private void txt_tongtienhang_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (txt_tongtienhang.Text.Length != 0)
                    txt_tongthanhtientinhthue.Text = (double.Parse(txt_tongtienhang.Text) + double.Parse(txt_tienthue.Text)).ToString("#,##0"); ;
            }
            catch(Exception){}
        }

        private void txt_khuyenmai_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (txt_khuyenmai.Text.Trim() != "")
                {
                    if (int.Parse(txt_khuyenmai.Text) != 0)
                    {
                        double thanhtien = double.Parse(txt_soluong.Text) * double.Parse(txt_dongia.Text) - double.Parse(txt_soluong.Text) * double.Parse(txt_dongia.Text) * float.Parse(txt_khuyenmai.Text) / 100;
                        txt_thanhtien1.Text = thanhtien.ToString("#,##0");
                    }
                    else
                    {
                        txt_thanhtien1.Text = (int.Parse(txt_dongia.Text) * int.Parse(txt_soluong.Text)).ToString("#,##0");
                    }
                }
            }
            catch (Exception ex) { logger.Error("Error: "+ex.Message); }
        }

        private void bt_xemin_Click(object sender, EventArgs e)
        {
            //dua len report
            try
            {
                DataSet ds = new DataSet();
                string mahdnhap = "";
                ds.ReadXml(new StringReader(xuly.selectqueryByText("select top 1 mahdnh from hoadonnhaphang order by mahdnh desc")));
                if (ds.Tables.Count > 0)
                {
                    mahdnhap = ds.Tables[0].Rows[0][0].ToString();
                    Report.frm_InPhieuNhap phieunhap = new Report.frm_InPhieuNhap();
                    phieunhap.mahdnhap = mahdnhap;
                    phieunhap.ShowDialog();
                }

                //Xoa cac thong tin tien sau khi da luu va in phieu
                txt_tongtienhang.Text = "0";
                txt_tongthanhtientinhthue.Text = "0";
                txt_mucthue.Text = "0";
                txt_tiendadua.Text = "0";
                txt_tienconlai.Text = "0";
                txt_tienthue.Text = "0";
                txt_tienbangchu.Text = "không đồng chẳn.";

                //Xoa tat cac thong tin sau khi da Luu hoa don va In phieu
                if (checkbox_PhieuDHNCC.Checked == true)
                {
                    Load_DSPhieuDatNCCChuaGiao();
                    gv_hdnhaphang.DataSource = null;
                }
                else
                {
                    gv_hdnhaphang.Rows.Clear();
                }
            }
            catch (Exception ex)
            {
            }
        }

        private void checkbox_PhieuDHNCC_CheckedChanged(object sender, EventArgs e)
        {
            errorProvider1.Clear();
            if (checkbox_PhieuDHNCC.Checked == true)
            {
                mcbb_PhieuDHNCC.Enabled = true;

                //Khoi tao Enable cho cac control
                KhoaConTrol(false);
            }
            else
            {
                mcbb_PhieuDHNCC.Enabled = false;
                gv_hdnhaphang.DataSource = null;
                KhoaConTrol(true);
                //Xoa thong tin lien quan
                mcbb_PhieuDHNCC.Text = "";
                txt_tongtienhang.Text = "0";
                txt_tongthanhtientinhthue.Text = "0";
                txt_diachi.Text = "";
                txt_TienTamUng.Text = "0";
                cmb_khohang.Text = "";
                cmb_nhacungcap.Text = "";
                txt_tiendadua.Text = "0";
                txt_tienconlai.Text = "0";
                txt_mucthue.Text = "0";
                txt_tienthue.Text = "0";
                txt_tienbangchu.Text = "không đồng chẳn.";
            }
        }

        private void Load_DSPhieuDatNCCChuaGiao()
        {
            try
            {
                RadMultiColumnComboBoxElement multiColumnComboElement = this.mcbb_PhieuDHNCC.MultiColumnComboBoxElement;
                multiColumnComboElement.DropDownSizingMode = SizingMode.UpDownAndRightBottom;
                multiColumnComboElement.DropDownMinSize = new Size(300, 200);

                string sql = "Select hd.MaDHNCC,NgayThangDH,MaKho,MaNCC,TamUng "
                             + "from PhieuDatHangNCC hd,CTDatHangNCC ct "
                             + "where hd.MaDHNCC = ct.MaDHNCC and  DaGiao = 'false' "
                             + "group by hd.MaDHNCC,NgayThangDH,MaKho,MaNCC,TamUng";
                DataSet ds = new DataSet();
                ds.ReadXml(new StringReader(xuly.selectqueryByText(sql)));
                if (ds.Tables.Count > 0)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        ds.Tables[0].Rows[i]["NgayThangDH"] =DateTime.Parse(ds.Tables[0].Rows[i]["NgayThangDH"].ToString()).ToShortDateString();
                    }
                    mcbb_PhieuDHNCC.DataSource = ds.Tables[0];
                    mcbb_PhieuDHNCC.DisplayMember = "MaDHNCC";
                    mcbb_PhieuDHNCC.ValueMember = "MaDHNCC";
                    mcbb_PhieuDHNCC.SelectedIndex = -1;
                }
                FilterDescriptor des_mh = new FilterDescriptor(this.mcbb_PhieuDHNCC.ValueMember, FilterOperator.StartsWith, string.Empty);
                mcbb_PhieuDHNCC.EditorControl.FilterDescriptors.Add(des_mh);
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        private void mcbb_PhieuDHNCC_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                //Chinh do dai cua cac cot trong muiltcombobox                
                if (mcbb_PhieuDHNCC.Text.Trim() == "")
                {
                    gv_hdnhaphang.DataSource = null;
                    cmb_khohang.Text = "";
                    cmb_nhacungcap.Text = "";
                    txt_diachi.Text = "";
                    txt_TienTamUng.Text = "0";
                    txt_tongtienhang.Text = "0";
                    txt_tongthanhtientinhthue.Text = "0";
                }
                else
                {
                    //Lay thong thong tin Kho hang va Nha Cung Cap                    
                    for (int i = 0; i < cmb_nhacungcap.EditorControl.Rows.Count; i++)
                    {
                        if (cmb_nhacungcap.EditorControl.Rows[i].Cells["MaNCC"].Value.ToString().Trim() == mcbb_PhieuDHNCC.EditorControl.Rows[mcbb_PhieuDHNCC.SelectedIndex].Cells["MaNCC"].Value.ToString().Trim())
                            cmb_nhacungcap.EditorControl.Rows[i].IsCurrent = true;                        
                    }
                    for (int i = 0; i < cmb_khohang.EditorControl.Rows.Count; i++)
                    {
                        if (cmb_khohang.EditorControl.Rows[i].Cells["MaKho"].Value.ToString().Trim() == mcbb_PhieuDHNCC.EditorControl.Rows[mcbb_PhieuDHNCC.SelectedIndex].Cells["MaKho"].Value.ToString().Trim())
                            cmb_khohang.EditorControl.Rows[i].IsCurrent = true;
                    }
                    txt_TienTamUng.Text = double.Parse(mcbb_PhieuDHNCC.EditorControl.Rows[mcbb_PhieuDHNCC.SelectedIndex].Cells["TamUng"].Value.ToString()).ToString("#,##0");

                    //Load du lieu cac mat hang chua giao len Gridview                    
                    string sql = "Select ct.MaMH,TenMH,SoLuong,DonGia,ChietKhau,ThanhTien "
                                 + "from PhieuDatHangNCC hd,CTDatHangNCC ct,MatHang mh "
                                 + "where hd.MaDHNCC = ct.MaDHNCC and mh.MaMH = ct.MaMH and DaGiao = 'false' and hd.MaDHNCC = '"+mcbb_PhieuDHNCC.SelectedValue.ToString().Trim()+"' "
                                 + "group by ct.MaMH,TenMH,SoLuong,DonGia,ChietKhau,ThanhTien";
                    DataSet ds = new DataSet();
                    ds.ReadXml(new StringReader(xuly.selectqueryByText(sql)));
                    if (ds.Tables.Count > 0)
                    {
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            ds.Tables[0].Rows[i]["DonGia"] = double.Parse(ds.Tables[0].Rows[i]["DonGia"].ToString()).ToString("#,##0");
                            ds.Tables[0].Rows[i]["ChietKhau"] = float.Parse(ds.Tables[0].Rows[i]["ChietKhau"].ToString()).ToString("0.0");
                            ds.Tables[0].Rows[i]["ThanhTien"] = (double.Parse(ds.Tables[0].Rows[i]["DonGia"].ToString()) * double.Parse(ds.Tables[0].Rows[i]["SoLuong"].ToString()) - double.Parse(ds.Tables[0].Rows[i]["DonGia"].ToString()) * double.Parse(ds.Tables[0].Rows[i]["SoLuong"].ToString()) * float.Parse(ds.Tables[0].Rows[i]["ChietKhau"].ToString())).ToString("#,##0");                            
                        }
                        gv_hdnhaphang.DataSource = ds.Tables[0];                        
                    }
                    //Tao them nut xoa mat hang
                    if (gv_hdnhaphang.Columns.GetColumnByFieldName("xoa").Length == 0)
                    {
                        GridViewCommandColumn btnColumn = new GridViewCommandColumn();
                        btnColumn.FieldName = "xoa";
                        btnColumn.Name = "xoa";
                        btnColumn.UseDefaultText = true;
                        btnColumn.DefaultText = "Xóa";
                        gv_hdnhaphang.Columns.Insert(gv_hdnhaphang.Columns.Count, btnColumn);
                    }
                    //Tao STT trong Gridview va cap nhat lai Tong Tien hang
                    if (gv_hdnhaphang.Rows.Count > 0)
                    {
                        tongtienhang = 0;
                        tongtien = 0;
                        for (int i = 0; i < gv_hdnhaphang.Rows.Count; i++)
                        {
                            gv_hdnhaphang.Rows[i].Cells["STT"].Value = i + 1;
                            //Tinh Tong Tien
                            tongtienhang += double.Parse(gv_hdnhaphang.Rows[i].Cells["ThanhTien"].Value.ToString());
                        }
                        txt_tongtienhang.Text = tongtienhang.ToString("#,##0");
                        tongtien = tongtienhang + double.Parse(txt_tienthue.Text) - double.Parse(txt_TienTamUng.Text);
                        txt_tongthanhtientinhthue.Text = tongtien.ToString("#,##0");
                        txt_tienbangchu.Text = So_chu(tongtien);
                    }                    
                }
            }
            catch(Exception ex)
            {
                logger.Error("Error " + ex.Message);
            }

        }

        private void KhoaConTrol(bool khoa)
        {
            cmb_nhacungcap.Enabled = khoa;
            cmb_tenmathang.Enabled = khoa;
            cmb_khohang.Enabled = khoa;
            txt_soluong.Enabled = khoa;
            txt_dongia.Enabled = khoa;
            txt_khuyenmai.Enabled = khoa;
            txt_thanhtien1.Enabled = khoa;
            bt_chuyenxuong.Enabled = khoa;
            ddl_dvt.Enabled = khoa;
        }        

        private void btn_XemDMMatHang_Click(object sender, EventArgs e)
        {
            FormPhu_MatHang phuMH = new FormPhu_MatHang();
            phuMH.ShowDialog();
        }

        private void bt_timkiem_Click(object sender, EventArgs e)
        {
            frmBC_Chitietnhapkho ctnh = new frmBC_Chitietnhapkho();
            ctnh.Show();
        }

        private void txt_tongthanhtientinhthue_TextChanged(object sender, EventArgs e)
        {
            try
            {
                txt_tienbangchu.Text = So_chu(double.Parse(txt_tongthanhtientinhthue.Text));
            }
            catch (Exception) { }
        }

        private void gv_hdnhaphang_CellValueChanged(object sender, GridViewCellEventArgs e)
        {
            errorProvider1.Clear();
            try
            {
                if (Regex.IsMatch(gv_hdnhaphang.CurrentRow.Cells["SoLuong"].Value.ToString().Trim(), @"^[0-9,',']{0,5}$") == false || int.Parse(gv_hdnhaphang.CurrentRow.Cells["SoLuong"].Value.ToString()) <= 0)
                {
                    lbl_ThongBao.Text = "Số lượng nhập vào phải lớn hơn không (số lượng > 0) và là con số nguyên. Vui lòng nhập lại";
                    errorProvider1.RightToLeft = false;
                    errorProvider1.SetError(lbl_ThongBao, "Xem lại thông tin trên lưới.");
                    return;
                }
                if (Regex.IsMatch(gv_hdnhaphang.CurrentRow.Cells["DonGia"].Value.ToString(), @"^[0-9,',']{0,9}$") == false || int.Parse(gv_hdnhaphang.CurrentRow.Cells["DonGia"].Value.ToString()) <= 0)
                {
                    lbl_ThongBao.Text = "Đơn giá nhập vào phải lớn hơn không (số lượng > 0) và là con số nguyên. Vui lòng nhập lại";
                    errorProvider1.RightToLeft = false;
                    errorProvider1.SetError(lbl_ThongBao, "Xem lại thông tin trên lưới.");
                    return;
                }
                if (Regex.IsMatch(gv_hdnhaphang.CurrentRow.Cells["Chietkhau"].Value.ToString().Trim(), @"^(\d{1,2})$") == false || int.Parse(gv_hdnhaphang.CurrentRow.Cells["ChietKhau"].Value.ToString()) > 50)
                {
                    lbl_ThongBao.Text = "Số chiết khấu từ 0 - 50 %";
                    errorProvider1.RightToLeft = false;
                    errorProvider1.SetError(lbl_ThongBao, "Xem lại thông tin trên lưới.");
                    return;
                }
                lbl_ThongBao.Text = "Thông báo!";
                errorProvider1.RightToLeft = true;
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        private void gv_hdnhaphang_CellEndEdit(object sender, GridViewCellEventArgs e)
        {
            try
            {
                double tongtien_sausua = 0;
                double dongia = double.Parse(gv_hdnhaphang.CurrentRow.Cells["DonGia"].Value.ToString());
                int soluong = int.Parse(gv_hdnhaphang.CurrentRow.Cells["Soluong"].Value.ToString().Trim());
                float khuyenmai = float.Parse(gv_hdnhaphang.CurrentRow.Cells["ChietKhau"].Value.ToString());
                double thanhtien = (soluong * dongia) - ((soluong * dongia) * khuyenmai) / 100;
                gv_hdnhaphang.CurrentRow.Cells["ThanhTien"].Value = thanhtien.ToString("#,##0");

                for (int i = 0; i < gv_hdnhaphang.Rows.Count; i++)
                {
                    gv_hdnhaphang.Rows[i].Cells["SoLuong"].Value = double.Parse(gv_hdnhaphang.Rows[i].Cells["SoLuong"].Value.ToString()).ToString("#,##0");
                    gv_hdnhaphang.Rows[i].Cells["DonGia"].Value = double.Parse(gv_hdnhaphang.Rows[i].Cells["DonGia"].Value.ToString()).ToString("#,##0");
                    tongtien_sausua += double.Parse(gv_hdnhaphang.Rows[i].Cells["ThanhTien"].Value.ToString());
                }
                txt_tongtienhang.Text = tongtien_sausua.ToString("#,##0");
            }
            catch
            {
            }
        }

        private void bt_home_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
